'use strict'
const SUN = require('../base/sun')
const mongodb = require('mongodb')
let dbConfig = SUN.serConfig.dbConfig
class DbClient {
    constructor() {
        this.db = null
        this._connection()
    }

    /**
     * 数据库连接构造函数
     */

    _connection() {
        let self = this
        mongodb.MongoClient.connect(`mongodb://${dbConfig.host}:${dbConfig.port}/${dbConfig.dbName}`, function(err, db) {
            if (!err) {
                self.db = db
                SUN.emit('dbConnect', db)
                console.info('连接数据库成功', `mongodb://${dbConfig.host}:${dbConfig.port}/${dbConfig.dbName}`)
                db.on('close', function() {
                    console.info('数据库断开连接', `mongodb://${dbConfig.host}:${dbConfig.port}/${dbConfig.dbName}`)
                    SUN.emit('dbClose')
                })
            } else {
                console.error(`连接数据库 mongodb://${dbConfig.port}/${dbConfig.dbName}错误:${err.message}`)
                process.exit(1)
            }
        })
    }
}
exports.dbClient = new DbClient()
